package com.sugar.real.estate.module.business.util;

import com.sugar.real.estate.module.business.controller.app.infocls.vo.AppOpenedCityRespVO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Y.sugar
 * @date 2021/4/2 14:49
 */
public class TreeUtil {

    public static List<AppOpenedCityRespVO> listConvertTree(List<AppOpenedCityRespVO> dataList) {
        return getChildList(0L, dataList);
    }

    private static List<AppOpenedCityRespVO> getChildList(Long parentId, List<AppOpenedCityRespVO> remainList) {

        // 获取到该父 id 的所有子部门，并排序
        List<AppOpenedCityRespVO> parentIdChildList = remainList
                .stream()
                .filter(o -> o.getParentId().equals(parentId))
                .collect(Collectors.toList());

        // 移除已经获取的数据
        remainList.removeAll(parentIdChildList);

        parentIdChildList.forEach(o -> {
            Long id = o.getId();

            List<AppOpenedCityRespVO> childList = remainList
                    .stream()
                    .filter(u -> u.getParentId().equals(id))
                    .collect(Collectors.toList());

            if (!childList.isEmpty()) {
                o.setChildList(childList);
                childList.forEach(u -> getChildList(id, remainList));
            }
        });

        return parentIdChildList;
    }

}
